package com.gliese.bambook.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.gliese.bambook.object.Snbc;

public class SnbUtils {
	private static Log log = LogFactory.getLog(SnbUtils.class);

	public static String getSnbTodayAbsPath(Snbc snbc) {
		String userHome = System.getProperty("user.home");
		String fileSeparator = System.getProperty("file.separator");
		String snbSinaTodayPath = userHome + fileSeparator + ".snb"
				+ fileSeparator + snbc.getUrl().replace("http://", "")
				+ fileSeparator
				+ DateFormatUtils.ISO_DATE_FORMAT.format(new Date())
				+ fileSeparator;
		return snbSinaTodayPath;
	}

	/**
	 * if file not exists ,then create 
	 * @param doc
	 * @param path
	 */
	public static void wirteDocument(Document doc, String path) {
		try {
			File file = new File(path);
			try {
				if (!file.exists())
					file.createNewFile();
			} catch (IOException e) {
				log.error("create " + path + " Error:" + e.getMessage());
				System.exit(0);
			}
			FileOutputStream fileOutputStream = new FileOutputStream(path);
			OutputFormat outputFormat = new OutputFormat();
			outputFormat.setTrimText(true);
			outputFormat.setEncoding("UTF-8");
			XMLWriter xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
			xmlWriter.write(doc);
			xmlWriter.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {

		}
	}
}
